package com.baidu.sggc.service;

import com.baidu.sggc.data.req.AppInstanceListReq;
import com.baidu.sggc.data.req.ProductCreateReq;
import com.baidu.sggc.data.req.ProductListReq;
import com.baidu.sggc.data.req.ProductUpdateReq;
import com.baidu.sggc.data.resp.Page;
import com.baidu.sggc.entity.ProductInfo;
import com.baidu.sggc.entity.UserContext;
import com.baidu.sggc.mapper.ProductInfoMapper;
import com.baidu.sggc.third.ab.agent.AbAppInstanceApi;
import com.baidu.sggc.third.ab.agent.AppInstanceListReqDto;
import com.baidu.sggc.third.ab.agent.AppInstanceListRespDto;
import com.baidu.sggc.entity.vo.ProductInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 产品信息表 服务实现类
 * </p>
 *
 * @author lianglin
 * @since 2025-02-13
 */
@Slf4j
@Service
public class ProductInfoService {
  private static Logger logger = LoggerFactory.getLogger(ProductInfo.class);

  @Autowired
  private AbAppInstanceApi productApi;

  @Autowired
  private ProductInfoMapper productInfoMapper;

//  @Value("${third.ab.departmentId}")
//  private String departmentId;
  @Value("${third.ab.appInstanceAvatarUrl}")
  private String appInstanceAvatarUrl;
  @Value("${third.ab.appInstanceExamplePage}")
  private String appInstanceExamplePage;

  public List<ProductInfoVo> getAppInstanceList(AppInstanceListReq req) {
    AppInstanceListReqDto appInstanceListReqDto = new AppInstanceListReqDto();
    appInstanceListReqDto.setDepartmentId(req.getDepartmentId());
    appInstanceListReqDto.setPage(req.getPageNum());
    appInstanceListReqDto.setLimit(req.getPageSize());
    List<AppInstanceListRespDto.AppInstance> data = productApi.queryAppInstanceList(appInstanceListReqDto);
    return appInstanceToProductInfoVoList(data, req.getDepartmentId());
  }

  private List<ProductInfoVo> appInstanceToProductInfoVoList(List<AppInstanceListRespDto.AppInstance> data, String departmentId) {
    List<ProductInfoVo> productInfoVoList = null;
    if (data != null) {
      productInfoVoList = new ArrayList<>();
      for (AppInstanceListRespDto.AppInstance appInstance : data) {
        ProductInfoVo productInfoVo = new ProductInfoVo();
        productInfoVo.setDepartmentId(departmentId);
        if (appInstance.getAppId() != null && !appInstance.getAppId().isEmpty()) {
          productInfoVo.setProductId(appInstance.getAppId());
          productInfoVo.setProductUseUrl(appInstanceExamplePage + appInstance.getAppId());
        }
        if (appInstance.getName() != null && !appInstance.getName().isEmpty()) {
          productInfoVo.setProductName(appInstance.getName());
        }
        if (appInstance.getDesc() != null && !appInstance.getDesc().isEmpty()) {
          productInfoVo.setProductBrief(appInstance.getDesc());
        }
        if (appInstance.getAvatar() != null && !appInstance.getAvatar().isEmpty()) {
          productInfoVo.setProductImageUrl(appInstance.getAvatar());
        }else{
          productInfoVo.setProductImageUrl(appInstanceAvatarUrl);
        }
        if (appInstance.getTags() != null) {
          productInfoVo.setTags(String.join(",", appInstance.getTags()));
        }
        if (appInstance.getCopyPermission() != null){
          productInfoVo.setCopyPermission(appInstance.getCopyPermission());
        }
        if (appInstance.getTemplateName() != null && !appInstance.getTemplateName().isEmpty()){
          productInfoVo.setCreateTypeFilter(appInstance.getTemplateName());
        }
        productInfoVoList.add(productInfoVo);
      }
    }
    return productInfoVoList;
  }

  public Page<ProductInfoVo> getProductInfoList(ProductListReq req) {
    try {
      Thread.sleep(1000); // 模拟延时，便于压测
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }

    Page<ProductInfoVo> page;

    try {
      String keyWord = req.getKeyWord();
      if (StringUtils.isNotBlank(keyWord)) {
        // 对 LIKE 特殊字符转义
        keyWord = escapeLikeParam(keyWord.trim());
        req.setKeyWord(keyWord);
      }
      PageHelper.startPage(req.getPageNum(), req.getPageSize());
      List<ProductInfoVo> productInfoList = productInfoMapper.getProductInfoList(req);
      PageInfo<ProductInfoVo> pageInfo = new PageInfo<>(productInfoList);
      page = new Page<>(
              pageInfo.getTotal(),
              pageInfo.getList(),
              pageInfo.isHasNextPage()
      );
    } catch (Exception e) {
      logger.error("Select failed: " + e.getMessage());
      throw new RuntimeException("Select failed: ", e);
    }
    return page;
  }

  public static String escapeLikeParam(String param) {
    if (param == null) {
      return null;
    }
    // 只转义 %, _
    return param.replace("%", "\\%").replace("_", "\\_");
  }

  public ProductInfoVo getProductInfoById(Long id) {
    ProductInfoVo productInfoVo = null;
    try {
      LambdaQueryWrapper<ProductInfo> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(ProductInfo::getId, id)
              .eq(ProductInfo::getIsDel, 0);
      ProductInfo productInfo = productInfoMapper.selectOne(queryWrapper);
      if (productInfo != null) {
        productInfoVo = new ProductInfoVo();
        BeanUtils.copyProperties(productInfo, productInfoVo);
      }
    } catch (Exception e) {
      logger.error("Select failed: " + e.getMessage());
      throw new RuntimeException("Select failed: ", e);
    }
    return productInfoVo;
  }


  public boolean createProductInfo(ProductCreateReq req) {
    boolean b;
    try {
      ProductInfo productInfo = new ProductInfo();
      BeanUtils.copyProperties(req, productInfo);
      // 设置当前登录用户信息
      String userId = UserContext.getUserId();
      String userName = UserContext.getUserName();
      if (userId != null) {
        productInfo.setCreateId(userId);
      }
      if (userName != null) {
        productInfo.setCreateName(userName);
      }
      b = productInfoMapper.insert(productInfo) > 0;
    } catch (Exception e) {
      logger.error("Create failed: " + e.getMessage());
      throw new RuntimeException("Create failed: ", e);
    }
    return b;
  }

  public boolean updateProductInfoById(ProductUpdateReq req) {
    boolean b;
    try {
      ProductInfo productInfo = new ProductInfo();
      BeanUtils.copyProperties(req, productInfo);

      // 设置当前登录用户信息
      String userId = UserContext.getUserId();
      if (userId != null) {
        productInfo.setUpdateId(userId);
      }
      productInfo.setUpdateTime(LocalDateTime.now());
      b = productInfoMapper.updateByProductInfoId(productInfo) > 0;
    } catch (Exception e) {
      logger.error("Update failed: " + e.getMessage());
      throw new RuntimeException("Update failed: ", e);
    }
    return b;
  }

  public boolean deleteProductInfoById(ProductInfo req) {
    boolean b;
    try {
      b = productInfoMapper.deleteById(req) > 0;
    } catch (Exception e) {
      logger.error("Delete failed: " + e.getMessage());
      throw new RuntimeException("Delete failed: ", e);
    }
    return b;
  }
}
